using System;
using System.Collections.Generic;
using UnityEngine;

public class GGImageRequestCache : SingletonInit<GGImageRequestCache>
{
	public class CachedRequest
	{
		protected DateTime expireTime;

		public Texture2D cachedImage;

		public bool isExpired
		{
			get
			{
				return DateTime.Now > expireTime;
			}
		}

		public CachedRequest(Texture2D cachedImage, TimeSpan timeToLive)
		{
			this.cachedImage = cachedImage;
			expireTime = DateTime.Now + timeToLive;
		}

		public void Destroy()
		{
		}

		public void SetTimeToLive(TimeSpan timeToLive)
		{
			expireTime = DateTime.Now + timeToLive;
		}
	}

	protected GGRequestFileCache fileCache;

	private Dictionary<string, CachedRequest> cache = new Dictionary<string, CachedRequest>();

	public static TimeSpan InfiniteTimeToLive()
	{
		return TimeSpan.FromDays(100000.0);
	}

	public override void Init()
	{
		fileCache = new GGRequestFileCache();
		fileCache.filename = "imageCache.bytes";
		fileCache.Init();
	}

	public void Put(string key, Texture2D cachedImage, TimeSpan timeToLive, bool useFile)
	{
		if (!(cachedImage != null))
		{
			return;
		}
		GGDebug.DebugLog("IMAGE CACHE - Put into cache " + key);
		if (cache.ContainsKey(key))
		{
			CachedRequest cachedRequest = cache[key];
			if (cachedRequest.cachedImage != cachedImage)
			{
				cachedRequest.cachedImage = cachedImage;
			}
			cachedRequest.SetTimeToLive(timeToLive);
		}
		else
		{
			cache[key] = new CachedRequest(cachedImage, timeToLive);
		}
		if (useFile)
		{
			GGDebug.DebugLog("IMAGE CACHE - Put into FILE " + key);
			fileCache.Put(key, cachedImage.EncodeToPNG(), timeToLive);
		}
	}

	public void ClearCache()
	{
		foreach (CachedRequest value in cache.Values)
		{
			value.Destroy();
		}
		cache.Clear();
	}

	public Texture2D Get(string key)
	{
		CachedRequest cachedRequest = null;
		GGDebug.DebugLog("CACHE IMAGE-GET: " + key);
		if (!cache.ContainsKey(key))
		{
			byte[] array = fileCache.Get<byte[]>(key);
			if (array != null)
			{
				Texture2D texture2D = new Texture2D(0, 0);
				texture2D.LoadImage(array);
				Put(key, texture2D, fileCache.GetTimeToLive(key), false);
			}
		}
		if (cache.ContainsKey(key))
		{
			cachedRequest = cache[key];
			GGDebug.DebugLog("Cache Hit: " + key + ", expired " + cachedRequest.isExpired);
			if (cachedRequest.isExpired)
			{
				cachedRequest.Destroy();
				cache.Remove(key);
				return null;
			}
			return cachedRequest.cachedImage;
		}
		return null;
	}
}
